<template>
  <div class="my-container w-full h-full">
    <div class="top">
      <div class="back cursor-pointer" @click="back">
        <img
          class="w-12 h-12 lg:w-20 lg:h-20"
          src="/images/backIcon.png"
          alt=""
        />
        <span class="text-2xl lg:text-4xl">返回</span>
      </div>
      <h2 class="text-2xl lg:text-4xl">面象采集</h2>
    </div>
    <div class="main">
      <video id="video" :class="isWebCamera ? '' : 'is-web'" src=""></video>
      <div class="mask">
        <img src="/images/face-mask.png" alt="" />
      </div>
    </div>
    <button id="left" v-show="btnStat[stat].showLeft" @click="rePhoto">
      {{ btnStat[stat].leftText }}
    </button>
    <button id="right" v-show="btnStat[stat].showRight" @click="submit">
      {{ btnStat[stat].rightText }}
    </button>
    <MyAlert ref="myAlert" />
  </div>
</template>

<script setup>
import MyAlert from "@/components/alert/index.vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
const baseUrl = import.meta.env.BASE_URL;

const router = useRouter();

const getParams = ()=>{
  const url_string = window.location.href
  const url = new URL(url_string);
  return url.searchParams.get('usewebcamera');
}
const isWebCamera = getParams()

const myAlert = ref();
let imgData = "";
let stat = ref(0);
let btnStat = {
  0: {
    showLeft: false,
    showRight: true,
    leftText: "",
    rightText: "开始采集",
  },
  1: {
    showLeft: false,
    showRight: true,
    leftText: "",
    rightText: "识别中...",
  },
  2: {
    showLeft: true,
    showRight: true,
    leftText: "重新采集",
    rightText: "确认提交",
  },
};
let myFile = "";

const back = () => {
  router.replace("/");
};
const rePhoto = () => {
  const video = document.getElementById("video");
  video.play();
  stat.value = 0;
  showMyDialog = false;
};

const submit = () => {
  if (stat.value == 0) {
    return getFaceImg();
  }
  if (stat.value == 2) {
    return submitRes();
  }
};

const submitRes = () => {
  // return uploadImg()
  // setTimeout(() => {
  //     // localStorage.setItem("face", true);
  //     // localStorage.setItem("item", "face");

  // }, 2000);
  setTimeout(() => {
    let audio = document.getElementById("myAudio");
    audio.src = baseUrl + "/sources/face_complate.mp3";
    audio.muted = false;
    audio.play();
  }, 200);
  router.push("/");
};
const getFaceImg = async () => {
  const video = document.getElementById("video");

  //暂停视频，然后获取该帧视频的图片
  video.pause();
  imgData = getImgFromVideo(video);
  // console.log(imgData); 
  //调用舌象分析接口
  stat.value = 1;
  let res = await faceAnalysis();
  console.log(res);
  if (!res) {
    stat.value = 0;
    video.play();
    return;
  }
  // showDialog("采集完成");
  //如果分析失败，给出错误原因，并回滚状态
  // stat = 0
  // video.play()

  //分析成功用户决定重拍或者提交

  return (stat.value = 2);
};
const faceAnalysis = async () => {
  return new Promise((resolve, reject) => {
    uploadImg(resolve);
  });
};
const isDatou = true;//是否是大头设备
const getImgFromVideo = (video) => {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  if(isWebCamera){
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;


    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  }else{
    // 设置画布尺寸与旋转后的图像尺寸一致
  canvas.width = video.videoHeight;
  canvas.height = video.videoWidth;

  // 逆时针旋转90度
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(-90 * Math.PI / 180);
  ctx.drawImage(video, -video.videoWidth / 2, -video.videoHeight / 2);
  }
  

  
  //imgData是base64格式的图片
  const imgData = canvas.toDataURL("image/png");
  let arr = imgData.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  let file = new File([u8arr], "image.png", { type: mime });
  return file;
};
const uploadImg = (resolve) => {
  let formData = new FormData();
  formData.append("image", imgData);
  fetch("/sizhen/admin/api/upload_face_image", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${window.localStorage.getItem("token")}`,
    },
    body: formData,
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.code !== 0) {
        myAlert.value.showAlert(data.message);
        return resolve(false);
      }
      myAlert.value.showAlert("上传成功！");
      resolve(true);
    })
    .catch((err) => {
      myAlert.value.showAlert("上传图片失败");
      return resolve(false);
    });
};
const openVideo = () => {
  let constraints = {}
  if(isWebCamera){
    constraints = {
      video: true,
      audio: false,
    }
  }else{
    constraints = {
      video: {
        width:{
          exact:1600
        },
        height:{
          exact:1200
        }
      },
      audio: false,
    }
  }
  navigator.mediaDevices
    .getUserMedia(constraints)
    .then((stream) => {
      // Changing the source of video to current stream.
      video.srcObject = stream;
      video.addEventListener("loadedmetadata", () => {
        video.play();
        let audio = document.getElementById("myAudio");
        audio.src = baseUrl + "/sources/face.mp3";
        audio.muted = false;
        audio.play();
      });
    })
    .catch((err) => {
      myAlert.value.showAlert("摄像设备打开失败");
      return;
    });
};

onMounted(() => {
  openVideo();
});
</script>

<style scoped>
.is-web{
  width: min(100vh, 100vw) !important;
  height: min(100vh, 100vw) !important;
  
  transform: rotate(-90deg) !important;
  transform-origin: center !important;
}
#video{
  
}
video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  
}
.my-container .top {
  position: absolute;
  width: 100%;
  height: 15%;
  /* background: white; */
  /* position: relative; */
  display: flex;
  justify-content: flex-start;
  align-items: center;
  z-index: 2;
  top: 0;
  left: 0;
  /* color: white; */
}

.top .back {
  width: 20%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.top .back img {
  width: 4rem;
  margin-right: 1rem;
  cursor: pointer;
}

.back span {
  font-size: 2rem;
  color: white;
}

.top h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2rem;
  color: white;
}

#right {
  z-index: 2;
  cursor: pointer;
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 15%;
  height: 3rem;
  font-size: 1.5rem;
  background: linear-gradient(to right, rgb(150, 150, 249), rgb(105, 105, 252));
  /* background: blue; */
  border-radius: 2rem;
  border: none;
  color: white;
}

#left {
  z-index: 2;
  cursor: pointer;
  position: fixed;
  bottom: 2rem;
  left: 2rem;
  width: 15%;
  height: 3rem;
  font-size: 1.5rem;
  background: linear-gradient(to right, rgb(150, 150, 249), rgb(105, 105, 252));
  /* background: blue; */
  border-radius: 2rem;
  border: none;
  color: white;
}

button {
  width: 22.75vw !important;
  height: 6.64vw !important;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 3vw !important;
  border-radius: 100vw !important;
}

.main {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: 0;

  display: flex;
  justify-content: center;
  align-items: center;
}

/* video {
  width: 100%;
  height: 100%;
  object-fit: cover;
} */

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.2);

  display: flex;
  justify-content: center;
  align-items: center;
}

.mask > img {
  width: 40%;
}
</style>
